package com.os.opencv.java.chapter10;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class HoughLine2 {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("pics/goChild.png", Imgcodecs.IMREAD_GRAYSCALE);
        HighGui.imshow("src", src);
        HighGui.waitKey(0);

        //canny边缘检测并将结果存储为bgr图像
        Mat canny = new Mat();
        Mat dst = new Mat();
        Imgproc.Canny(src, canny, 50, 200, 3, false);
        Imgproc.cvtColor(canny, dst, Imgproc.COLOR_GRAY2BGR);

        //进行霍夫检测结果存储在lines中
        Mat lines = new Mat();
        Imgproc.HoughLines(canny, lines, 1, Math.PI/30, 300);

        //将检测结果用红线画出
        for(int n=0; n<lines.rows(); n++){
            double rho = lines.get(n, 0)[0];
            double theta = lines.get(n, 0)[1];
            double cos = Math.cos(theta);
            double sin = Math.sin(theta);
            double x0 = cos * rho;
            double y0 = sin * rho;
            double len = 800;

            Point pt1 = new Point(Math.round(x0+len*(-sin)), Math.round(y0 + len*(cos)));
            Point pt2 = new Point(Math.round(x0 - len*(-sin)), Math.round(y0-len*(cos)));
            Imgproc.line(dst, pt1, pt2, new Scalar(0,0,255), 3);
        }
        HighGui.imshow("detected lines", dst);
        HighGui.waitKey(0);
        System.exit(0);
    }
}
